<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\api\home;

use think\Controller;
use think\exception\HttpResponseException;
use think\facade\Cache;
use think\facade\Request;
use think\Response;
use EasyWeChat\Factory;
use think\Db;
use think\Image;
use think\File;
use app\api\home\WxBizDataCrypt;
use think\Queue;
use GuzzleHttp\json_decode;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
// 指定允许其他域名访问
header('Access-Control-Allow-Origin:*');
// 响应类型
header('Access-Control-Allow-Methods:*');
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with,content-type');
class Index extends Controller
{
    protected $responseType = 'json';
    protected $pageSize = 10;
    protected $url = 'https://jiayou.61hc.com/';
    protected $config = [
        'app_id'             => 'wx9336a4c10a45d3c6',
        'mch_id'             => '1676577564',
        'secret'             => 'd6c7a05332258581670072dd32fb3680',   
        'key'                => 'hGGiYH2AjYNWyRc5Pa0UNkwTH30nke9X',   // APIV2 密钥
        // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
        'cert_path' => '/www/wwwroot/admin/public/static/cert/apiclient_cert.pem', // XXX: 绝对路径！！！！
        'key_path' => '/www/wwwroot/admin/public/static/cert/apiclient_key.pem',      // XXX: 绝对路径！！！！
        
        // 下面为可选项
        // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        'response_type' => 'array',

        'log' => [
            'level' => 'debug',
            'file' => __DIR__.'/wechat.log',
        ],
    ];

    public function index(){
        $this->success('宜加油接口');
    }
    
    //优惠后的价格
    public function price_d(){
        $d=$this->request->param();
        $dept_id=isset($d['dept_id'])?$d['dept_id']:0;
        if(!$dept_id){  //通过加油站推断优惠力度
            $this->error('请选择加油站');
        }
        $dept=Db::name("dept")->find($dept_id);
        $prices=$d['prices'];
        if($prices<=0){
            $this->error('金额不能小于0');
        }
        $category=Db::name("category")->find($dept['type']);
        $price=$category['prices'];  //今日油价
        $down_prices=$category['down_prices'];  //今日优惠        
        $totalPrice=$prices*($price-$down_prices)/$price;
        $totalPrice=round($totalPrice,2);
        $this->success($totalPrice);      
    }
    
    
    public function  pay(){
        $d=$this->request->param();
        if(!isset($d['user_id']) || !$d['user_id']){
            $this->error('请登录',1000);
        }
        $app = Factory::payment($this->config);
        $out_trade_no = time() . rand(1000, 9999).rand(1000,9999);//订单号
        if(!isset($d['prices'])){
            $this->error('请输入金额');
        }
        $prices=$d['prices'];
        if($prices<=0){
            $this->error('金额不能小于0');
        }
        
        $user=Db::name("user")->find($d['user_id']);
        if($user['status']==0){
            $this->error('黑名单用户,禁止使用该小程序');
        }
        $dept_id=isset($d['dept_id'])?$d['dept_id']:0;
        if(!$dept_id){  //通过加油站推断优惠力度
            $this->error('请选择加油站');
        }
        $dept=Db::name("dept")->find($dept_id);
        $category=Db::name("category")->find($dept['type']);
        $price=$category['prices'];  //今日油价
        $down_prices=$category['down_prices'];  //今日优惠
        $num=$prices/$price;
        $num=round($num,2);
        
        $totalPrice=$prices*($price-$down_prices)*100/$price;
        $totalPrice=$totalPrice<=1?1:$totalPrice;
        $save_fee=$prices-$totalPrice;
        //查询空的加油卡号
        $time=date("Y-m-d H:i:s");
        $card=Db::name("card")
        ->where("expiry_time","<",$time)
        ->where("balance",">",$prices)
        ->order("balance desc")
        ->find();
        //halt(Db::name("card")->getLastSql());
        if(!$card){
            $this->error('加油卡余额不足，请联系管理员');
        }
        
        //锁定该卡时间
        Db::name("card")->where("id",$card['id'])->update([
            //"expiry_time"=>date("Y-m-d H:i:s",strtotime("+10 minutes"))
        ]);
        $domain = Request()->domain();
        $params = [
            'trade_type'       => 'JSAPI',
            'body'             => $dept['name'].'加油费用支付',
            'out_trade_no'     => $out_trade_no,
            'total_fee'        => (int)$totalPrice,
           // 'total_fee'        => 1,//金额
            'detail'           => '费用支付',
            'spbill_create_ip' => request()->ip(),
            'openid' => $user['openid'],
            'notify_url'         => $domain.'/api/index/pay_callback'
        ];
       $result = $app->order->unify($params);
       
       //halt($result);
        
        $jssdk = $app->jssdk;
       //  $config = $jssdk->appConfig($result['prepay_id']);  //app
        $result = $jssdk->bridgeConfig($result['prepay_id'], false);
        $date=date("Y-m-d H:i:s");        
        $order_id=Db::name("order")->insertGetId([
            'user_id'           => $d['user_id'],
            'out_trade_no'      => $out_trade_no,
            'total_fee'         => $totalPrice,
            'save_fee'         => $save_fee,
            'all_fee'         => $prices,
            'status'            => 0,
            'body'           => '费用支付',
            'detail'           => '费用支付',
            'create_time'           => $date,
            'update_time'           => $date,
            'category_id'           => $category['categoryId'],
            'num'           => $num,
            're_id'           => $user['re_id'],
            'card_id'           => $card['id'],
        ]);
        $datas=[
            "order_id"=>$order_id,
            "result"=>$result,
            "out_trade_no"  => $out_trade_no,
        ];
        $this->success($datas);        
    }
    
    
    //订单回调
    public function pay_callback(){
        $app=Factory::payment($this->config);
        
        $response = $app->handlePaidNotify(function($message, $fail)use ($app){
            
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order =  Db::name("order")->where(['out_trade_no'=>$message['out_trade_no']])->find();
            
            if (empty($order) || $order['status']==1) { // 如果订单不存在 或者 订单已经支付过了
                return 1;
            }
            
            if ($message['return_code'] === 'SUCCESS') {  //更新订单状态
                $time=date("Y-m-d H:i:s",time());
                Db::name("order")->where("id",$order['id'])->update([
                    "status"=>1,
                    "pay_time"=>$time,
                ]);
                
                $total_fee=$order['total_fee']/100;                    
                //根据card调用支付二维码 写入数据库
                $card=Db::name("card")->find($order['card_id']);
                $header[]=$card['user_token'];
                $header[]="content-type:application/json";
                $infos=$this->jiayouka($card['body'],$header);
                $infos=json_decode($infos,true);  
                
                if(!isset($infos['qr_code'])){  //没有二维码  需要过期调试
                    Db::name("order")->where("id",$order['id'])->update([
                        "qr_code"=>'系统异常',
                    ]);
                }else{
                    Db::name("order")->where("id",$order['id'])->update([
                        "qr_code"=>$infos['qr_code'],
                        "server_time"=>$infos['server_time'],
                        "qr_code_md5"=>$infos['qr_code_md5'],
                        "update_time"=>$time,
                    ]);
                    
                    Db::name("card_log")->insert([
                        "order_id"=>$order['id'],
                        "card_id"=>$order['card_id'],
                        "qr_code"=>$infos['qr_code'],
                        "server_time"=>$infos['server_time'],
                        "qr_code_md5"=>$infos['qr_code_md5'],
                        "operation_type"=>$infos['operation_type'],
                        "qr_code_valid_period"=>$infos['qr_code_valid_period'],
                        "create_time"=>$time,
                        "money"=>$order['total_fee'],
                    ]);
                }
                
                //定时查询该卡余额 
                $jobHandlerClassName  = 'app\job\OrderJob';
                $jobQueueName  	  = "balance";
                $jobData       	  = [ 'card_id' => $order['card_id'],'order_id' => $order['id'] ] ;
                $isPushed =Queue::later(200,$jobHandlerClassName,$jobData, $jobQueueName);
                
                return true;
                
                // 用户支付失败
            } elseif ($message['return_code'] === 'FAIL') {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });
            
            $response->send(); // return $response;
    }
    //定时任务查询 余额   10分钟后
    public function job(){
        $jobHandlerClassName  = 'app\job\OrderJob';
        $jobQueueName  	  = "balance";
        $jobData       	  = [ 'card_id' => 1 ] ;
        $isPushed =Queue::later(180,$jobHandlerClassName,$jobData, $jobQueueName);
        //\think\Queue::push('app\job\OrderJob@reward',['order_id'=>$id,'user_id'=>$this->auth->id,'money'=>$pay['price']],'fx');
        return $isPushed;
    }
    
    
    public function  jiayouka($post_data,$header){
        set_time_limit(0);
//         $header=null;
//         $header[]="Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySW5mbyI6IlYvLzFPVCsrWlVSUXlZd0RzcWc4UHRFVGdPVjZxSm5Wbzc1M1NvdU9vNFhtLzViWlhLa2w0SUJsdTZUWlBQNVJ4elAwa3V4R0lSNDVDYjZGSzBzMDBRPT0iLCJleHAiOjE3MTczMTc1MDgsIm5iZiI6MTcxNjQ1MzUwOH0.sClCHLYVNaose2PIq9fsPUsvCz-NB3XtQURYmT9nuYQ";
//         $header[]="content-type:application/json";
        $url="https://b2bvcard.shell.com.cn/bhz-vcs-service/apis/v1/purchases";
//         $post_data=[
//             "operation_type"=>"1",
//             "user_id"=>"1230511859187576832",
//             "pan_code"=>"51ft8dmw",
//             "card_binding_mode"=>1,
//             "cellphone"=>"13880446756",
//             "is_reflush_qr_code"=>0,
//             "auth_info"=>[
//                 "auth_mode"=>"password",
//                 "password"=>"n8wZzTUkqgLNVnDJcjNMiw==",
//             ],
//             "plate_number_info"=>[],
//         ];
        //$post_data=json_encode($post_data);
        $info=$this->jiayouUrl($url,$post_data,$header);
        //halt($info);
        //$info=json_decode($info,true);  
        return $info;
    }
    
    
    
    public function jiayouUrl($c_url, $c_url_data = false, $header = false) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$c_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $c_url_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $result = curl_exec($ch);
        curl_close ($ch);
        unset($ch);
        
        return $result;
    }
    
    
    //查询卡余额
    public  function balance($card_id=1){
         $card=Db::name("card")->find($card_id);
         $header[]=$card['user_token'];
         $header[]="content-type:application/json";
         $url="https://b2bvcard.shell.com.cn/bhz-vcs-service/apis/v1/availablebalance?pan_code=".$card['pan_code']."&user_id=".$card['you_user_id']."&cellphone=".$card['cellphone']."&org_id=".$card['org_id'];
         //$url="https://b2bvcard.shell.com.cn/bhz-vcs-service/apis/v1/availablebalance?pan_code=51ft8dmw&user_id=1230511859187576832&cellphone=13880446756&org_id=51510000";
       //  halt($url); 
         $info = $this->getUrl($url,$header);
         halt($info);
    }
    
    //订单回调
    public function pay_callback1(){
        $app=Factory::payment($this->config);
        $order =  Db::name("order")->where(['out_trade_no'=>'171639158087712216'])->find();
        
//         if (empty($order) || $order['status']==1) { // 如果订单不存在 或者 订单已经支付过了
//             return 1;
//         }
        
            $time=date("Y-m-d H:i:s",time());
            Db::name("order")->where("id",$order['id'])->update([
                "status"=>1,
                "pay_time"=>$time,
            ]);
            
            $total_fee=$order['total_fee']/100;
            //根据card调用支付二维码 写入数据库
            $card=Db::name("card")->find($order['card_id']);
            $header[]=$card['user_token'];
            $header[]="content-type:application/json";
            $infos=$this->jiayouka($card['body'],$header);
            
            $infos=json_decode($infos,true);
           // halt($infos);
            if(!isset($infos['qr_code'])){  //没有二维码
                Db::name("order")->where("id",$order['id'])->update([
                    "qr_code"=>'系统异常',
                ]);
            }else{
                Db::name("order")->where("id",$order['id'])->update([
                    "qr_code"=>$infos['qr_code'],
                    "server_time"=>$infos['server_time'],
                    "qr_code_md5"=>$infos['qr_code_md5'],
                ]);
                
                Db::name("card_log")->insert([
                    "order_id"=>$order['id'],
                    "card_id"=>$order['card_id'],
                    "qr_code"=>$infos['qr_code'],
                    "server_time"=>$infos['server_time'],
                    "qr_code_md5"=>$infos['qr_code_md5'],
                    "operation_type"=>$infos['operation_type'],
                    "qr_code_valid_period"=>$infos['qr_code_valid_period'],
                    "create_time"=>$time,
                ]);
            }
            
            
            //定时查询该卡余额
            $jobHandlerClassName  = 'app\job\OrderJob';
            $jobQueueName  	  = "balance";
            $jobData       	  = [ 'card_id' => $order['card_id'],'order_id' => $order['id'] ] ;
            $isPushed =Queue::later(200,$jobHandlerClassName,$jobData, $jobQueueName);
    }
    

   
    /**
     * 操作成功返回的数据
     * @param string $msg   提示信息
     * @param mixed $data   要返回的数据
     * @param int   $code   错误码，默认为1
     * @param string $type  输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function success($data = null,$code = 200,$msg = '',$type = null, array $header = [],$ret=null)
    {
        $this->result($data, $code, $msg, $type, $header,$ret);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg   提示信息
     * @param mixed $data   要返回的数据
     * @param int   $code   错误码，默认为0
     * @param string $type  输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function error($msg = '',$code = 0,$data = null, $type = null, array $header = [])
    {
        $this->result($data,$code,$msg,$type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型，支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($data, $code = 0,$msg = '', $type = '', array $header = [],$ret=null)
    {
        $result = [
            'code' => $code,
            'message'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
            'ret' => $ret,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : (\request()->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode']))
        {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        }
        else
        {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    // 首页数据接口
    public function index_data(){
        
        $d=$this->request->param();
        
        $banner=Db::name("banners")
        ->alias('a')
        ->join("admin_attachment b","a.recommendPic=b.id",'left')
        ->field("a.*,concat('$this->url',b.path) url")
        ->select();


//         $news=Db::name("news")
//         ->alias('a')
//         ->order("a.id desc")->limit(3)->select();

        $lng=$this->request->param('positionX');
        $lat=$this->request->param('positionY');
        if(!$lng){
            $this->error('请打开定位');
        }
        $name= $this->request->param('name','');
        $where=['status'=>1];
        if($name){
            $where['name']=['like',"%$name%"];
        }
        $sql="ROUND(
        6378.138 * 2 * ASIN(
        SQRT(POW(SIN(({$lat} * PI() / 180 - lat * PI() / 180) / 2), 2) + COS({$lat} * PI() / 180) * COS(lat * PI() / 180) * POW(SIN(({$lng} * PI() / 180 - lng * PI() / 180) / 2), 2))
        ) * 1000
        ) AS juli";
        
        
        $list=Db::name("dept")
        ->alias("a")
        ->join("category b","a.type=b.categoryId","left")
        ->field(['a.id','a.name','a.addr','a.lat','a.lng','a.addr_address','a.type','b.prices','b.down_prices',$sql])
        ->order("juli,id desc")
        //->limit(10)
        ->select(); 
        $user_id=isset($d['user_id'])?$d['user_id']:0;
        foreach ($list as $k=>&$v){
            $v['juli']=round($v['juli']/1000,2)."公里"; 
        }
        
        
        $data['banner']=$banner;
       // $data['news']=$news;
        $data['list']=$list;

        //halt($data);
        return $this->success($data);
    }

    //获取用户信息
    public function  get_user_info(){
        $d=$this->request->param();
        $user=Db::name("user")->find($d['user_id']);
        return $this->success($user);
    }
    
    public function  banners(){
        $banner=Db::name("banners")
        ->alias('a')
        ->join("admin_attachment b","a.recommendPic=b.id",'left')
        ->field("a.*,concat('$this->url',b.path) url")
        ->select();
        
        return $this->success($banner);
    }
    
    public function category(){
        $data=Db::name("category")
        ->select();
        return $this->success($data);
    }
    
    //注销
    public function user_disable(){
        $d=$this->request->param();
        $r=Db::name("user")->where("id",$d['user_id'])
        ->update([
            "status"=>0,
            "mobile"=>null,
            "update_time"=>date("Y-m-d H:i:s"),
        ]);
        
        $this->success($r);
    }
    /**
     * 修改会员个人信息--微信
     */
    public function wxregister()
    {
            $data = $this->request->param();
            //数据存入数据库
            $recommend_id=isset($data['id'])?$data['id']:null;
            //检查是否存在用户
            $user = Db::name('user')->where(['openid'=>$data['openId']])->find();
            $userInfo=json_decode($data['rawData'],true);
            //halt($userInfo);
            if (!empty($user))
            {
                Db::name('user')->where(['openid'=>$data['openId']])->update([
                    'nickname'=> $userInfo['nickName'],
                    'gender'=>$userInfo['gender'],
                    'avatar'=>$userInfo['avatarUrl'],
                    'province'=>$userInfo['province'],
                    'city'=>$userInfo['city'],
                    'openid'=>$data['openId'],
                ]);
            }
            else
            {
                Db::name('user')->insert([
                    'nickname'=> $userInfo['nickName'],
                    'username'=> $userInfo['nickName'],
                    'gender'=>$userInfo['gender'],
                    'avatar'=>$userInfo['avatarUrl'],
                    'province'=>$userInfo['province'],
                    'city'=>$userInfo['city'],
                    'openid'=>$data['openId'],
                    'recommend_id'=>$recommend_id,
                    'createtime'=>time(),
                    'create_time'=>date("Y-m-d H:i:s"),
                ]);

            }
            $user_info = Db::name('user')->where(['openid'=>$data['openId']])->find();
            $this->success($user_info);
       
    }
    
    /**
     * 小程序获取用户手机号
     */
    public function wxapplet_phone()
    {
        $d=$this->request->param();
        $code = $d['code'];
        $user_id = $d['user_id'];
        $wxConfig = $this->config;
        $token=$this->getWxAccessToken();
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $token;
        $data['code'] = $code;
        $info = $this->postUrl($url,json_encode($data));
        $tmpinfo = json_decode($info, true);
        $code = $tmpinfo['errcode'];
        $phoneNumber = "";
        $phoneNumber = $tmpinfo['phone_info']['phoneNumber'] ?? "";
        
        
        
        if ($code == '0' && $phoneNumber) {
            Db::name("user")->where("id",$user_id)->update([
                "mobile"=>$phoneNumber,
                "update_time"=>date("Y-m-d H:i:s"),
            ]);
            
            $user=Db::name("user")->find($user_id);
            $this->success($user);
        } else {
            $this->error('获取手机号失败');
        }
       
        
        
    }
    
    
    /**
     * 小程序获取用户信息
     */
    public function wxapplet_info()
    {
        $d=$this->request->param();
        $code = $d['code'];
        $wxConfig = $this->config;
        
        $wx = file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid='.$wxConfig['app_id'].'&secret='.$wxConfig['secret'].'&js_code='.$code.'&grant_type=authorization_code');
        
        /**
         * openid	string	用户唯一标识
         * session_key	string	会话密钥
         * unionid	string	用户在开放平台的唯一标识符，在满足 UnionID 下发条件的情况下会返回，详见 UnionID 机制说明。
         * errcode	number	错误码
         * errmsg	string	错误信息
         **/
        $array = json_decode($wx,true);
        if (!isset($array['session_key']))
        {
            $this->error($msg="服务器发生错误！".$array['errcode']);
        }
        $this->success($array);
    }
    
    private function decryUser($appid ,$sessionKey ,$encryptedData ,$iv)
    {

        $pc = new WxBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        return $data ;
    }
    
    public function register()
    {
        $data = $this->request->param();
        //校验数据
        $code          = $data['code'];
        $iv            = $data['iv'];
        $iv = str_replace(' ', '+', $iv);
        $encryptedData = $data['encryptedData'];
        $encryptedData = str_replace(' ', '+', $encryptedData);
        $recommend_id=isset($data['recommend_id'])?(int)$data['recommend_id']:null;
        $wxConfig = $this->config;
        $appid  = $wxConfig['app_id'];
        $secret = $wxConfig['secret'];
        $url    = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
       
        $res = json_decode(file_get_contents($url),true);
       // halt($res);
        $session_key = $res['session_key'];
        $openid=$res['openid'];
        $ret = $this->decryUser($appid,$session_key ,$encryptedData ,$iv) ;
        $userInfo = json_decode($ret,true) ;
            //检查是否存在用户
        $user = Db::name('user')->where(['openid'=>$openid])->find();
            if($recommend_id){
                $re_user=Db::name("user")->find($recommend_id);
                $re_id=$re_user['re_id'];
            }else{
                $re_id=1;
                $recommend_id=143;
            }
            
            if (!empty($user))
            {
                if($user['status']==0){
                    $this->error('黑名单用户,禁止使用该小程序');
                }
                
                Db::name('user')->where(['openid'=>$openid])->update([
                    //'nickname'=> $userInfo['nickName'],
                    //'gender'=>$userInfo['gender'],
                    //'avatar'=>$userInfo['avatarUrl'],
                    //'province'=>$userInfo['province'],
                    //'city'=>$userInfo['city'],
                    //'openid'=>$openid,
                ]);
            }
            else
            {
                Db::name('user')->insert([
                    'nickname'=> $userInfo['nickName'],
                    'username'=> $userInfo['nickName'],
                    'gender'=>$userInfo['gender'],
                    'avatar'=>$userInfo['avatarUrl'],
                    'province'=>$userInfo['province'],
                    'city'=>$userInfo['city'],
                    'openid'=>$openid,
                    'recommend_id'=>$recommend_id,
                    're_id'=>$re_id,
                    'createtime'=>time(),
                    'create_time'=>date("Y-m-d H:i:s"),
                ]);
                
            }
            $user_info = Db::name('user')->where(['openid'=>$openid])->find();
            $this->success($user_info);
       
    }

    
//     public function register1()
//     {
//         $data = $this->request->param();
//         //校验数据
//         $sessionKey = $data['session_key'];
//         $signature = sha1($data['rawData'].$sessionKey);
//         $recommend_id=isset($data['recommend_id'])?$data['recommend_id']:null;
//         if ($signature != $data['signature'])
//         {
//             $this->error($msg="数据被篡改，用户系统信息不能与微信同步！");
//         }
        
//         $wxConfig = $this->config;
//         $pc = new WxBizDataCrypt($wxConfig['app_id'], $sessionKey);
//         $datas = null;
//         $errCode = $pc->decryptData($data['encryptedData'], $data['iv'], $datas);
//         if ($errCode == 0) {
//             //数据存入数据库
//             $userInfo=json_decode($datas,true);
            
//             //检查是否存在用户
//             $user = Db::name('user')->where(['openid'=>$userInfo['openId']])->find();
//             if($recommend_id){
//                 $re_user=Db::name("user")->find($recommend_id);
//                 $re_id=$re_user['re_id'];
//             }else{
//                 $re_id=1;
//             }
            
//             if (!empty($user))
//             {
//                 if($user['status']==0){
//                     $this->error('黑名单用户,禁止使用该小程序');
//                 }
                
//                 Db::name('user')->where(['openid'=>$userInfo['openId']])->update([
//                     'nickname'=> $userInfo['nickName'],
//                     'gender'=>$userInfo['gender'],
//                     'avatar'=>$userInfo['avatarUrl'],
//                     'province'=>$userInfo['province'],
//                     'city'=>$userInfo['city'],
//                     'openid'=>$userInfo['openId'],
//                 ]);
//             }
//             else
//             {
//                 Db::name('user')->insert([
//                     'nickname'=> $userInfo['nickName'],
//                     'username'=> $userInfo['nickName'],
//                     'gender'=>$userInfo['gender'],
//                     'avatar'=>$userInfo['avatarUrl'],
//                     'province'=>$userInfo['province'],
//                     'city'=>$userInfo['city'],
//                     'openid'=>$userInfo['openId'],
//                     'recommend_id'=>$recommend_id,
//                     're_id'=>$re_id,
//                     'createtime'=>time(),
//                     'create_time'=>date("Y-m-d H:i:s"),
//                 ]);
                
//             }
//             $user_info = Db::name('user')->where(['openid'=>$userInfo['openId']])->find();
//             $this->success($user_info);
//         } else {
//             $this->error($msg=$errCode);
//         }
//     }
    
    
    //修改信息
    public function update_user(){
        $d=$this->request->param();
        $user_id=$d['user_id'];
        unset($d['user_id']);
        //unset($d['use_status']);
        $r=Db::name("user")->where("id",$user_id)->update($d);
        $user=Db::name("user")->where("id",$user_id)->find();
        
        $this->success($user);
    }




    public function postUrl($c_url, $c_url_data = false, $header = false) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$c_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $c_url_data);
        $result = curl_exec($ch);
        curl_close ($ch);
        unset($ch);
        
        return $result;
    }

    public function getUrls($url, $header = false) {
        $ch = curl_init();
        $c_url = $url;
        ///$c_url_data = "account=omysy&password=123456&mobile=13880446756&content=111&action=send";
        curl_setopt($ch, CURLOPT_URL,$c_url);
        //curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//添加头信息
        $result = curl_exec($ch);
        $output = json_decode($result,true);
        curl_close ($ch);
        unset($ch);
        return $output;
    }


    public function genwxcode(){
        header("Content-Type: image/jpeg;text/html; charset=utf-8");
        $d=$this->request->param();  //生成二维码
        $miniProgram = Factory::miniProgram($this->config);
        $a=$miniProgram->app_code->getQrCode('pages/index/index?recommend_id='.$d['user_id']);

        echo ($a);exit();
    }
   //我的二维码
    public function genwxcodes(){

        
//         $miniProgram = Factory::miniProgram($this->config);
//         $a=$miniProgram->app_code->getQrCode('pages/index/index?recommend_id='.$d['user_id']);
        $d=$this->request->param();  //生成二维码
        if(!isset($d['user_id'])){
            $this->error('请登陆');
        }
        
        $domain = Request()->domain();
        $path=PUBLIC_PATH;
        $url='uploads/store/'.$d['user_id'].'.png';
        // halt($path.$url);
        if(!file_exists($path.$url)){
            $path="/pages/index/index?recommend_id=".$d['user_id'];
            $factory=Factory::miniProgram($this->config);
            $response = $factory->app_code->getQrCode($path);
            if ($response  instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $response->saveAs('uploads/store',$d['user_id'].'.png');
            }
        }
        $this->success($domain."/".$url);
    }

     //上传图片
    public function upload_picture(){

        $file = $this->request->file("file");
        if (empty($file)) {
            $this->error('请选择上传文件');
         }

               // 移动到框架应用根目录/public/uploads/ 目录下
         $info = $file->move(config('upload_path') . DIRECTORY_SEPARATOR . 'images');
              if ($info) {
                   $data="$this->url".'uploads/images/' . str_replace('\\', '/', $info->getSaveName());
                   $this->success($data,200,'文件上传成功',null,[],0);
            } else {      // 上传失败获取错误信息
                 $this->error($file->getError());
           }

    }
    
    
    public function upload_file(){
        
        $file = $this->request->file("file");
        if (empty($file)) {
            $this->error('请选择上传文件');
        }
        
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(config('upload_path') . DIRECTORY_SEPARATOR . 'files');
        if ($info) {
            $data['url']="$this->url".'uploads/files/' . str_replace('\\', '/', $info->getSaveName());
            $data['name']=$info->getFilename();
            $data['info']=$info->getInfo();
            $this->success($data,200,'文件上传成功',null,[],0);
        } else {      // 上传失败获取错误信息
            $this->error($file->getError());
        }
        
    }

    
    public function upload_avatar(){
        
        $file = $this->request->file("file");
        if (empty($file)) {
            $this->error('请选择上传文件');
        }
        
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(config('upload_path') . DIRECTORY_SEPARATOR . 'images');
        if ($info) {
            $names=str_replace('\\', '/', $info->getSaveName());
            $data['0']['url']="$this->url".'uploads/images/' . $names;
            
            $attr=explode(".", $names);
            $newnames=$attr['0']."veeki".".png";
            
            $this->yuanjiao(config('upload_path') . DIRECTORY_SEPARATOR . 'images/'. $names,config('upload_path') . DIRECTORY_SEPARATOR . 'images/'. $newnames);
            
            $data['0']['new']="$this->url".'uploads/images/' . $newnames;
            $this->success($data,200,'文件上传成功',null,[],0);
        } else {      // 上传失败获取错误信息
            $this->error($file->getError());
        }
        
    }
    
      
    
    //加油站列表
    public function dept_list(){
        $list=Db::name("dept")
        ->order("id desc")
        ->select();
        return $this->success($list);
        
    }
    
    //加油站详情
    public function dept_detials(){
        $d=$this->request->param();
        $id=isset($d['id'])?$d['id']:0;
        $list=Db::name("dept")
        ->alias("a")
        ->join("category b","a.type=b.categoryId","left")
        ->where("a.id",$id)
        ->field("a.*,b.name cate_name,b.prices,b.down_prices")
        ->find();
        return $this->success($list);
        
    }
    
    function tree($array, $pid)
    {
        $tree = array();
        foreach ($array as $key => $value) {
            if ($value['pid'] == $pid) {
                $value['child'] = $this->tree($array, $value['id']);
                if (!$value['child']) {
                    unset($value['child']);
                }
                $tree[] = $value;
            }
        }
        return $tree;
    }

    protected function geturl($url,$headerArray){
        //$headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if($headerArray){
            curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        }
        
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }

    protected function getWxAccessToken()
    {
//         $accessToken = Cache::get("wx_access_token");
//         if (empty($accessToken))
//         {
//             // 获取 access token 实例
//             $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->config['app_id'].'&secret='.$this->config['secret'];
//             $rs = $this->geturl($url);
//             $accessToken = $rs['access_token'];
//             Cache::set("wx_access_token",$accessToken,3600);
//         }
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->config['app_id'].'&secret='.$this->config['secret'];
        $rs = $this->geturl($url,null);
        $accessToken = $rs['access_token'];
        return $accessToken;
    }

    public function checkTextContent($content='1')
    {
        $accessToken = $this->getWxAccessToken();
        $url = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token='.$accessToken;
        $rs = $this->postUrl($url,[
            //"access_token" => $accessToken,
            "content" => $content
        ]);
        
        $rs = json_decode($rs,true);
        //halt($accessToken);
        // 合法内容
        return $rs['errcode'];
    }   
    
    
    //我的邀请列表
    public function my_recommend_list(){
        
        $d=$this->request->param();
        $user_id=(int)$d['user_id'];
        $page=isset($d['page'])?$d['page']:1;
        $size=isset($d['size'])?$d['size']:100;
        
        $list=Db::name('user')
        ->alias("a")
        ->where([
            "recommend_id"=>$user_id,
        ])
        ->order("id desc")
        ->page($page,$size)
        ->select();
        $this->success($list);
    }
    
    //我的所有邀请列表
    public function my_re_list(){
        
        $d=$this->request->param();
        $user_id=(int)$d['user_id'];
        $page=isset($d['page'])?$d['page']:1;
        $size=isset($d['size'])?$d['size']:100;
        
        $list=Db::name('user')
        ->alias("a")
        ->where([
            "re_id"=>$user_id,
        ])
        ->order("id desc")
        ->page($page,$size)
        ->select();
        $this->success($list);
    }
    
    
    //我的所有订单列表
    public function my_order_list(){
        
        $d=$this->request->param();
        $user_id=(int)$d['user_id'];
        $page=isset($d['page'])?$d['page']:1;
        $size=isset($d['size'])?$d['size']:100;
        
        $list=Db::name('order')
        ->alias("a")
        ->where([
            "user_id"=>$user_id,
            "status"=>1,
        ])
        ->page($page,$size)
        ->order("id desc")
        ->select();
        //halt(Db::name('order')->getLastSql());
        $this->success($list);
    }
    //我的订单详情 包括二维码
    public function get_order_orcode(){
        
        $d=$this->request->param();
        $order_id=(int)$d['order_id'];
        
        $list=Db::name('order')
        ->alias("a")
        ->find($order_id);
        
//         $card_log=Db::name("card_log")
//         ->where("order_id",$order_id)
//         ->order("id descd")
//         ->find();
        $this->success($list);
    }
    
    
    

    //用户协议
    public function yonghuxieyi(){
        $list=Db::name("admin_config")->where("id",5)->field("id,title,value")->find();
        return $this->success($list);
    }
    //显示
    public function web_site_show(){
        $list=Db::name("admin_config")->where("id",47)->value("value");
        return $this->success($list);
    }
    
    //显示
    public function web_site_show1(){
        $list=Db::name("admin_config")->where("id",48)->value("value");
        return $this->success($list);
    }
    
    
    //显示
    public function web_site_show2(){
        $list=Db::name("admin_config")->where("id",49)->value("value");
        return $this->success($list);
    }
    //合同文书模板下载
    public function web_site_show3(){
        $list=Db::name("admin_config")->where("id",50)->value("value");
        return $this->success($list);
    }
    
    //客服电话
    public function web_service_phone(){
        $list=Db::name("admin_config")->where("id",46)->field("id,title,value")->find();
        return $this->success($list);
    }
    
    //关于我们
    public function aboutus(){
        $list=Db::name("admin_config")->where("id",9)->field("id,title,value")->find();
        return $this->success($list);
    }
    
    
    //隐私协议
    public function yinsixieyi(){
        $list=Db::name("admin_config")->where("id",42)->field("id,title,value")->find();
        return $this->success($list);
    }
    
    
    //服务协议
    public function fwxy(){
        $list=Db::name("admin_config")->where("id",45)->field("id,title,value")->find();
        return $this->success($list);
    }
    
}
